package com.hm.hiedict.net;

import com.hm.hiedict.util.HiExecutor;
import com.hm.hiedict.util.HiSearchWordCallback;
import com.hm.hiedict.util.HiWordData;
import ohos.data.rdb.RdbStore;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

public class HiWeb {
    private String word;
    private RdbStore store;
    private HiSearchWordCallback callback;

    public HiWeb(String word, RdbStore store,
                         HiSearchWordCallback callback){
        word = word.toLowerCase();
        this.word = word;
        this.store = store;
        this.callback = callback;
    }

    public void getWebWord(){
        HiExecutor.runBG(new Runnable() {
            @Override
            public void run() {
                HandleWebWord();
            }
        });
    }

    private void HandleWebWord(){
        try {
            // 获取搜索结果(html形式)
            Document doc = Jsoup.connect("https://iciba.com/word?w=" + word).get();
            Elements ulElements = doc.getElementsByClass("Mean_part__1RA2V");
            // 将网络单词信息保存到本地的SQL语句
            String insertSQL = "insert into t_words(word, type, meanings) values(?,?,?);";
            List<HiWordData> hiWordDataList = new ArrayList<>();
            for (Element ulElement:ulElements){
                // 获取单词的每一个词性和中文解释
                Elements liElements = ulElement.getElementsByTag("li");
                // 对每一个词性进行迭代
                for (Element liElement:liElements){
                    HiWordData hiWordData = new HiWordData();
                    Elements iElements = liElement.getElementsByTag("i");
                    for (Element iElement:iElements){
                        // 获取词性
                        hiWordData.type = iElement.text();
                        break;
                    }
                    Elements divElements = liElement.getElementsByTag("div");
                    for (Element divElement:divElements){
                        //提取词性对应的中文解释
                        hiWordData.meanings = divElement.text();
                        break;
                    }
                    hiWordDataList.add(hiWordData);
                    store.executeSql(insertSQL, new String[]{word, hiWordData.type, hiWordData.type});
                }
                break;
            }
            callback.onSuccessResult(word, hiWordDataList);
        } catch (Exception e) {
            callback.onFailResult(e.toString());
            e.printStackTrace();
        }
    }
}
